package uk.co.tarbard.svnreporter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import nu.xom.Attribute;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Text;
import uk.co.tarbard.svnreporter.logentries.LogEntry;

public class XMLMarshaller implements IXMLMarshaller {

	final int MAX_TITLE_LENGTH = 10;

	public String createXML(List<LogEntry> logEntries) {
		Element root = new Element("data");
		Document document = new Document(root);

		for (LogEntry entry : logEntries) {
			String entryDate = formatDate(entry.getDate()).toString();

			Element event = new Element("event");
			event.addAttribute(new Attribute("author", entry.getAuthor()));
			event.addAttribute(new Attribute("start", entryDate));
			event.addAttribute(new Attribute("title", entry.getRevision() + ": " + createShortTitle(entry)));
			String message = entry.getMessage();
			if (message.length() == 0){
				message = "No Message";
			}
			event.appendChild(new Text(message+ "<hr/>" + "Author: " + entry.getAuthor()) );
			root.appendChild(event);
		}
		return document.toXML().trim();
	}

	/**
	 * Truncates the message to MAX_TITLE_LENGTH characters and adds ... to enable it to be used as
	 * a title
	 */
	private String createShortTitle(LogEntry entry) {
		String message = entry.getMessage();
		int messageLength = message.length();
		int lengthTotake = messageLength < MAX_TITLE_LENGTH ? messageLength : MAX_TITLE_LENGTH;

		String truncatedTitle = message.substring(0, lengthTotake);
		if (truncatedTitle.length() < messageLength)
			truncatedTitle += "...";

		return truncatedTitle;
	}

	String formatDate(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("E MMM d H:mm:ss z yyyy", Locale.UK);
		format.setTimeZone(TimeZone.getTimeZone("GMT"));
		return format.format(date);
	}

}
